from flask import Blueprint, request, jsonify
from datetime import datetime
import logging
from ..database import mongo_collection
from ..config import Config
from bson.objectid import ObjectId
from ..utils import admin_required, log_admin_operation
from ..utils.ip_utils import get_client_ip

admin_feedback_bp = Blueprint('admin_feedback', __name__)
logger = logging.getLogger('AdminFeedbackAPI')

@admin_feedback_bp.route('/v1/list', methods=['GET'])
@admin_required
def admin_list_feedback(admin_id, admin_level):
    """
    管理员获取反馈列表接口
    请求示例：/api/v1/admin/feedback/list?status=未处理&type=BUG&page=1&page_size=20
    
    参数说明：
    - status: 状态筛选 (可选)
    - type: 类型筛选 (可选)
    - user_id: 用户ID筛选 (可选)
    - page: 页码，默认1
    - page_size: 每页数量，默认20
    
    权限说明：
    - 1级管理员：可查看所有反馈
    - 非1级管理员：只能查看分配给自己的反馈
    """
    try:
        # 获取查询参数
        status = request.args.get('status')
        feedback_type = request.args.get('type')
        user_id = request.args.get('user_id')
        
        # 获取分页参数
        try:
            page = int(request.args.get('page', 1))
            page_size = int(request.args.get('page_size', 20))
            if page < 1 or page_size < 1:
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="list_feedback",
                    details={"error": "页码和每页数量必须为正整数"},
                    status="failed",
                    resource_type="feedback"
                )
                return jsonify(
                    code=40010,
                    message="页码和每页数量必须为正整数"
                ), 400
        except ValueError:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="list_feedback",
                details={"error": "页码和每页数量必须为整数"},
                status="failed",
                resource_type="feedback"
            )
            return jsonify(
                code=40010,
                message="页码和每页数量必须为整数"
            ), 400
        
        # 构建查询条件
        query = {}
        if status:
            valid_status = ['未处理', '处理中', '已回复']
            if status not in valid_status:
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="list_feedback",
                    details={"error": f"无效的状态值: {status}"},
                    status="failed",
                    resource_type="feedback"
                )
                return jsonify(
                    code=40016,
                    message=f"无效的状态值，有效值为: {', '.join(valid_status)}"
                ), 400
            query["status"] = status
            
        if feedback_type:
            valid_types = ['BUG', '建议', '投诉']
            if feedback_type not in valid_types:
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="list_feedback",
                    details={"error": f"无效的反馈类型: {feedback_type}"},
                    status="failed",
                    resource_type="feedback"
                )
                return jsonify(
                    code=40016,
                    message=f"无效的反馈类型，有效值为: {', '.join(valid_types)}"
                ), 400
            query["type"] = feedback_type
        
        if user_id:
            try:
                query["user_id"] = int(user_id)
            except ValueError:
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="list_feedback",
                    details={"error": "用户ID必须为整数"},
                    status="failed",
                    resource_type="feedback"
                )
                return jsonify(
                    code=40007,
                    message="用户ID必须为整数"
                ), 400
        
        # 根据管理员级别添加筛选条件
        if admin_level >= 2:
            # 非1级管理员只能查看分配给自己的反馈
            try:
                query["assigned_admin_id"] = int(admin_id)
            except ValueError:
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="list_feedback",
                    details={"error": "管理员ID格式错误"},
                    status="failed",
                    resource_type="feedback"
                )
                return jsonify(
                    code=40007,
                    message="管理员ID格式错误"
                ), 400
        
        # 从MongoDB获取反馈数据
        with mongo_collection(Config.MONGODB_COLLECTIONS["user_feedback"]) as collection:
            # 获取总数
            total_count = collection.count_documents(query)
            
            # 计算总页数
            total_pages = (total_count + page_size - 1) // page_size if total_count > 0 else 1
            
            # 获取分页数据
            skip = (page - 1) * page_size
            feedback_list = list(collection.find(query).sort("submit_time", -1).skip(skip).limit(page_size))
            
            # 格式化数据
            result_list = []
            for item in feedback_list:
                result_list.append({
                    "feedback_id": item["feedback_id"],
                    "user_id": item["user_id"],
                    "title": item["title"],
                    "content": item["content"],
                    "type": item["type"],
                    "status": item["status"],
                    "submit_time": item["submit_time"].isoformat() if isinstance(item["submit_time"], datetime) else item["submit_time"],
                    "contact": item.get("contact"),
                    "satisfaction": item.get("satisfaction"),
                    "device_id": item.get("device_id"),
                    "phonenumber": item.get("phonenumber"),
                    "attachment_url": item.get("attachment_url"),
                    "assigned_admin_id": item.get("assigned_admin_id"),
                    "assigned_admin_name": item.get("assigned_admin_name"),
                    "assign_time": item["assign_time"].isoformat() if item.get("assign_time") and isinstance(item["assign_time"], datetime) else item.get("assign_time"),
                    "last_update_time": item["last_update_time"].isoformat() if item.get("last_update_time") and isinstance(item["last_update_time"], datetime) else item.get("last_update_time")
                })
            
            # 记录操作成功
            log_admin_operation(
                admin_id=admin_id,
                operation="list_feedback",
                details={
                    "query": {
                        "status": status,
                        "type": feedback_type,
                        "user_id": user_id,
                        "admin_level_filter": admin_level != 1
                    },
                    "page": page,
                    "page_size": page_size,
                    "total": total_count
                },
                status="success",
                resource_type="feedback"
            )
            
            return jsonify({
                "code": 0,
                "message": "获取反馈列表成功",
                "total": total_count,
                "page": page,
                "page_size": page_size,
                "total_pages": total_pages,
                "feedback_list": result_list
            }), 200
                
    except Exception as e:
        logger.exception(f"管理员获取反馈列表异常: {str(e)}")
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="list_feedback",
            details={"error": str(e)},
            status="failed",
            resource_type="feedback"
        )
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试"
        ), 500

@admin_feedback_bp.route('/v1/update_status', methods=['POST'])
@admin_required
def update_feedback_status(admin_id, admin_level):
    """
    管理员更新反馈状态接口
    请求示例：
    {
        "feedback_id": 3,
        "status": "处理中"
    }
    """
    try:
        # 验证请求数据
        if not request.is_json:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="update_feedback_status",
                details={"error": "请求必须为JSON格式"},
                status="failed",
                resource_type="feedback"
            )
            return jsonify(
                code=Config.ERROR_CODES['INVALID_JSON'][0],
                message=Config.ERROR_CODES['INVALID_JSON'][1]
            ), 400
            
        data = request.get_json()
        
        # 校验必要字段
        required_fields = ['feedback_id', 'status']
        if missing := [f for f in required_fields if f not in data]:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="update_feedback_status",
                details={"error": f"缺少必要字段: {', '.join(missing)}"},
                status="failed",
                resource_type="feedback"
            )
            return jsonify(
                code=Config.ERROR_CODES['MISSING_FIELD'][0],
                message=f"{Config.ERROR_CODES['MISSING_FIELD'][1]}: {', '.join(missing)}"
            ), 400
        
        feedback_id = data['feedback_id']
        status = data['status']
        
        # 验证状态值
        valid_status = ['未处理', '处理中', '已回复']
        if status not in valid_status:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="update_feedback_status",
                details={
                    "feedback_id": feedback_id,
                    "status": status,
                    "error": f"无效的状态值: {status}"
                },
                status="failed",
                resource_type="feedback",
                resource_id=feedback_id
            )
            return jsonify(
                code=40016,
                message=f"无效的状态值，有效值为: {', '.join(valid_status)}"
            ), 400
            
        # 验证feedback_id格式
        try:
            feedback_id = int(feedback_id)
        except:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="update_feedback_status",
                details={
                    "feedback_id": feedback_id,
                    "error": "无效的反馈ID格式"
                },
                status="failed",
                resource_type="feedback",
                resource_id=feedback_id
            )
            return jsonify(
                code=40009,
                message="无效的反馈ID格式"
            ), 400
        
        # 更新MongoDB中的状态
        with mongo_collection(Config.MONGODB_COLLECTIONS["user_feedback"]) as collection:
            # 先检查反馈是否存在
            feedback = collection.find_one({"feedback_id": feedback_id})
            
            if not feedback:
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="update_feedback_status",
                    details={
                        "feedback_id": feedback_id,
                        "status": status,
                        "error": "未找到对应的反馈记录"
                    },
                    status="failed",
                    resource_type="feedback",
                    resource_id=feedback_id
                )
                return jsonify({
                    "code": 40404,
                    "message": "未找到对应的反馈记录"
                }), 404
            
            # 更新状态
            result = collection.update_one(
                {"feedback_id": feedback_id},
                {"$set": {"status": status}}
            )
            
            if result.modified_count > 0:
                logger.info(f"反馈状态更新成功 反馈ID:{feedback_id} 状态:{status}")
                
                # 记录操作成功
                log_admin_operation(
                    admin_id=admin_id,
                    operation="update_feedback_status",
                    details={
                        "feedback_id": feedback_id,
                        "old_status": feedback.get("status"),
                        "new_status": status,
                        "user_id": feedback.get("user_id")
                    },
                    status="success",
                    resource_type="feedback",
                    resource_id=feedback_id
                )
                
                return jsonify({
                    "code": 0,
                    "message": "反馈状态更新成功"
                }), 200
            else:
                logger.warning(f"反馈状态未更新 反馈ID:{feedback_id}")
                
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="update_feedback_status",
                    details={
                        "feedback_id": feedback_id,
                        "status": status,
                        "error": "反馈状态未更新，可能已经是相同值"
                    },
                    status="failed",
                    resource_type="feedback",
                    resource_id=feedback_id
                )
                
                return jsonify({
                    "code": 40004,
                    "message": "反馈状态未更新，可能已经是相同值"
                }), 400
                
    except Exception as e:
        logger.exception(f"更新反馈状态异常: {str(e)}")
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="update_feedback_status",
            details={
                "feedback_id": feedback_id if 'feedback_id' in locals() else None,
                "status": status if 'status' in locals() else None,
                "error": str(e)
            },
            status="failed",
            resource_type="feedback",
            resource_id=feedback_id if 'feedback_id' in locals() else None
        )
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试"
        ), 500

@admin_feedback_bp.route('/v1/reply', methods=['POST'])
@admin_required
def reply_feedback(admin_id, admin_level):
    """
    管理员回复反馈接口
    请求示例：
    {
        "feedback_id": 3,
        "content": "感谢您的反馈，我们已经修复了这个问题，请更新到最新版本尝试。",
        "reply_by": "技术支持"
    }
    """
    try:
        # 验证请求数据
        if not request.is_json:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="reply_feedback",
                details={"error": "请求必须为JSON格式"},
                status="failed",
                resource_type="feedback"
            )
            return jsonify(
                code=Config.ERROR_CODES['INVALID_JSON'][0],
                message=Config.ERROR_CODES['INVALID_JSON'][1]
            ), 400
            
        data = request.get_json()
        
        # 校验必要字段
        required_fields = ['feedback_id', 'content']
        if missing := [f for f in required_fields if f not in data]:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="reply_feedback",
                details={"error": f"缺少必要字段: {', '.join(missing)}"},
                status="failed",
                resource_type="feedback"
            )
            return jsonify(
                code=Config.ERROR_CODES['MISSING_FIELD'][0],
                message=f"{Config.ERROR_CODES['MISSING_FIELD'][1]}: {', '.join(missing)}"
            ), 400
        
        feedback_id = data['feedback_id']
        content = data['content']
        reply_by = data.get('reply_by', '客服')
        
        # 验证feedback_id格式
        try:
            feedback_id = int(feedback_id)
        except:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="reply_feedback",
                details={
                    "feedback_id": feedback_id,
                    "error": "无效的反馈ID格式"
                },
                status="failed",
                resource_type="feedback",
                resource_id=feedback_id
            )
            return jsonify(
                code=40009,
                message="无效的反馈ID格式"
            ), 400
        
        # 验证反馈是否存在
        with mongo_collection(Config.MONGODB_COLLECTIONS["user_feedback"]) as collection:
            feedback = collection.find_one({"feedback_id": feedback_id})
            
            if not feedback:
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="reply_feedback",
                    details={
                        "feedback_id": feedback_id,
                        "error": "未找到对应的反馈记录"
                    },
                    status="failed",
                    resource_type="feedback",
                    resource_id=feedback_id
                )
                return jsonify({
                    "code": 40404,
                    "message": "未找到对应的反馈记录"
                }), 404
            
            # 获取更多反馈信息
            user_id = feedback.get("user_id")
            feedback_title = feedback.get("title", "")
            feedback_content = feedback.get("content", "")
            feedback_type = feedback.get("type", "")
            feedback_submit_time = feedback.get("submit_time")
            
            # 更新反馈状态为"已回复"和最后更新时间
            now = datetime.now()
            collection.update_one(
                {"feedback_id": feedback_id},
                {"$set": {
                    "status": "已回复",
                    "last_update_time": now
                }}
            )
        
        # 添加回复到回复集合
        with mongo_collection(Config.MONGODB_COLLECTIONS["feedback_replies"]) as collection:
            reply_data = {
                "feedback_id": feedback_id,
                "content": content,
                "reply_by": reply_by,
                "reply_time": now,
                "admin_id": admin_id,
                "user_id": user_id,
                "feedback_title": feedback_title,
                "feedback_content": feedback_content,
                "feedback_type": feedback_type,
                "feedback_submit_time": feedback_submit_time,
                "admin_level": admin_level,
                "reply_ip": get_client_ip(),
                "reply_user_agent": request.user_agent.string if request.user_agent else None
            }
            
            result = collection.insert_one(reply_data)
            
            if result.inserted_id:
                logger.info(f"反馈回复成功 反馈ID:{feedback_id} 用户ID:{user_id}")
                
                # 记录操作成功
                log_admin_operation(
                    admin_id=admin_id,
                    operation="reply_feedback",
                    details={
                        "feedback_id": feedback_id,
                        "reply_id": str(result.inserted_id),
                        "user_id": user_id,
                        "reply_by": reply_by,
                        "feedback_title": feedback_title
                    },
                    status="success",
                    resource_type="feedback",
                    resource_id=feedback_id
                )
                
                return jsonify({
                    "code": 0,
                    "message": "反馈回复成功",
                    "reply_id": str(result.inserted_id)
                }), 201
            else:
                logger.error("反馈回复失败")
                
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="reply_feedback",
                    details={
                        "feedback_id": feedback_id,
                        "error": "数据库操作失败"
                    },
                    status="failed",
                    resource_type="feedback",
                    resource_id=feedback_id
                )
                
                return jsonify({
                    "code": 50003,
                    "message": "数据库操作失败"
                }), 500
                
    except Exception as e:
        logger.exception(f"回复反馈异常: {str(e)}")
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="reply_feedback",
            details={
                "feedback_id": feedback_id if 'feedback_id' in locals() else None,
                "error": str(e)
            },
            status="failed",
            resource_type="feedback",
            resource_id=feedback_id if 'feedback_id' in locals() else None
        )
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试"
        ), 500

@admin_feedback_bp.route('/v1/get_replies', methods=['GET'])
@admin_required
def get_feedback_replies(admin_id, admin_level):
    """
    获取特定反馈的所有回复
    请求示例：/api/v1/admin/feedback/get_replies?feedback_id=4
    
    参数说明：
    - feedback_id: 反馈ID (必填)
    """
    try:
        # 获取feedback_id参数
        feedback_id_str = request.args.get('feedback_id')
        if not feedback_id_str:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="get_feedback_replies",
                details={"error": "缺少必要参数feedback_id"},
                status="failed",
                resource_type="feedback"
            )
            return jsonify(
                code=40009,
                message="缺少必要参数feedback_id"
            ), 400
            
        # 验证feedback_id格式
        try:
            feedback_id = int(feedback_id_str)
        except ValueError:
            # 记录操作失败
            log_admin_operation(
                admin_id=admin_id,
                operation="get_feedback_replies",
                details={
                    "feedback_id": feedback_id_str,
                    "error": "无效的反馈ID格式"
                },
                status="failed",
                resource_type="feedback",
                resource_id=feedback_id_str
            )
            return jsonify(
                code=40009,
                message="无效的反馈ID格式"
            ), 400
        
        # 验证反馈是否存在
        with mongo_collection(Config.MONGODB_COLLECTIONS["user_feedback"]) as collection:
            feedback = collection.find_one({"feedback_id": feedback_id})
            
            if not feedback:
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="get_feedback_replies",
                    details={
                        "feedback_id": feedback_id,
                        "error": "未找到对应的反馈记录"
                    },
                    status="failed",
                    resource_type="feedback",
                    resource_id=feedback_id
                )
                return jsonify({
                    "code": 40404,
                    "message": "未找到对应的反馈记录"
                }), 404
                
            # 检查权限（非1级管理员只能查看分配给自己的反馈的回复）
            if admin_level >= 2 and feedback.get("assigned_admin_id") != int(admin_id):
                # 记录操作失败
                log_admin_operation(
                    admin_id=admin_id,
                    operation="get_feedback_replies",
                    details={
                        "feedback_id": feedback_id,
                        "error": "无权限查看该反馈的回复"
                    },
                    status="failed",
                    resource_type="feedback",
                    resource_id=feedback_id
                )
                return jsonify({
                    "code": 40403,
                    "message": "无权限查看该反馈的回复"
                }), 403
        
        # 从回复集合中查询所有回复
        with mongo_collection(Config.MONGODB_COLLECTIONS["feedback_replies"]) as collection:
            replies = list(collection.find({"feedback_id": feedback_id}).sort("reply_time", 1))
            
            # 格式化回复数据
            formatted_replies = []
            for reply in replies:
                formatted_replies.append({
                    "reply_id": str(reply.get("_id")),
                    "feedback_id": reply.get("feedback_id"),
                    "content": reply.get("content"),
                    "reply_by": reply.get("reply_by"),
                    "reply_time": reply["reply_time"].isoformat() if isinstance(reply.get("reply_time"), datetime) else reply.get("reply_time"),
                    "admin_id": reply.get("admin_id")
                })
            
            # 记录操作成功
            log_admin_operation(
                admin_id=admin_id,
                operation="get_feedback_replies",
                details={
                    "feedback_id": feedback_id,
                    "reply_count": len(formatted_replies)
                },
                status="success",
                resource_type="feedback",
                resource_id=feedback_id
            )
            
            return jsonify({
                "code": 0,
                "message": "获取反馈回复成功",
                "feedback_id": feedback_id,
                "reply_count": len(formatted_replies),
                "replies": formatted_replies
            }), 200
                
    except Exception as e:
        logger.exception(f"获取反馈回复异常: {str(e)}")
        
        # 记录操作失败
        log_admin_operation(
            admin_id=admin_id,
            operation="get_feedback_replies",
            details={
                "feedback_id": feedback_id if 'feedback_id' in locals() else None,
                "error": str(e)
            },
            status="failed",
            resource_type="feedback",
            resource_id=feedback_id if 'feedback_id' in locals() else None
        )
        
        return jsonify(
            code=50000,
            message="系统繁忙，请稍后重试"
        ), 500 